import { Address, toNano } from '@ton/core';
import { TodoParent } from '../wrappers/TodoParent';
import { NetworkProvider } from '@ton/blueprint';

const parent_address = Address.parse('EQATUJOKkKLEBfF-Qw3z7QqP4Is-PUSH5VnH1-jHI-4ne3H7');

export async function run(provider: NetworkProvider, args: string[]) {
    // await deploy(provider);
    // await newTodo(provider);
    // await completeTodo(provider);
    await getNumTodos(provider);
    // await getTodoAddress(provider);
}

export async function deploy(provider: NetworkProvider) {
    const todoParent = provider.open(await TodoParent.fromInit());

    await todoParent.send(
        provider.sender(),
        {
            value: toNano('0.05'),
        },
        {
            $$type: 'Deploy',
            queryId: 0n,
        }
    );

    await provider.waitForDeploy(todoParent.address);
    // run methods on `todoParent`
}

export async function newTodo(provider: NetworkProvider) {
    const ui = provider.ui();

    if (!(await provider.isContractDeployed(parent_address))) {
        ui.write(`Error: Contract at address ${parent_address} is not deployed!`);
        return;
    }

    const todoParent = provider.open(TodoParent.fromAddress(parent_address));

    await todoParent.send(
        provider.sender(),
        {
            value: toNano('0.05'),
        },
        {
            $$type: 'NewTodo',
            task: 'eat',
        }
    );
}

export async function completeTodo(provider: NetworkProvider) {
    const ui = provider.ui();

    if (!(await provider.isContractDeployed(parent_address))) {
        ui.write(`Error: Contract at address ${parent_address} is not deployed!`);
        return;
    }

    const todoParent = provider.open(TodoParent.fromAddress(parent_address));

    await todoParent.send(
        provider.sender(),
        {
            value: toNano('0.05'),
        },
        {
            $$type: 'CompleteTodo',
            seqno: 2n,
        }
    );
}

async function getNumTodos(provider: NetworkProvider){
    const ui = provider.ui();

    if (!(await provider.isContractDeployed(parent_address))) {
        ui.write(`Error: Contract at address ${parent_address} is not deployed!`);
        return;
    }

    const todoParent = provider.open(TodoParent.fromAddress(parent_address));

    let val = await todoParent.getNumTodos();
    console.log("numTodos: " + val)
}

async function getTodoAddress(provider: NetworkProvider){
    const ui = provider.ui();

    if (!(await provider.isContractDeployed(parent_address))) {
        ui.write(`Error: Contract at address ${parent_address} is not deployed!`);
        return;
    }

    const todoParent = provider.open(TodoParent.fromAddress(parent_address));

    let val = await todoParent.getTodoAddress(1n);
    console.log("todoAddress: " + val)
}